<template>
  <div class="video-player-container" :class="{ 'mobile': isMobile }">
    <div class="video-section">
      <div v-if="loading" class="loading-overlay">
        <el-spinner />
      </div>
      
      <video
        ref="videoPlayer"
        class="video-js vjs-default-skin"
        controls
        preload="auto"
      >
        <source :src="videoUrl" type="video/mp4" />
      </video>
      
      <div v-if="error" class="error-message">
        <el-alert
          :title="error"
          type="error"
          show-icon
          @close="clearError"
        />
      </div>

      <div class="video-info">
        <h2>{{ lesson?.title }}</h2>
        <p>{{ lesson?.description }}</p>
      </div>
    </div>

    <div class="course-content">
      <h3>课程目录</h3>
      <el-tree
        v-loading="loading"
        :data="chapters"
        :props="defaultProps"
        @node-click="handleNodeClick"
        highlight-current
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span v-if="data.duration">({{ formatDuration(data.duration) }})</span>
          </span>
        </template>
      </el-tree>
    </div>

    <Chat
      v-if="showChat"
      :conversation-id="chatConversationId"
      :current-user-id="currentUserId"
      :recipient-id="course.instructorId"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useVideoStore } from '@/stores/video'
import { storeToRefs } from 'pinia'
import { useBreakpoints } from '@vueuse/core'
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import Chat from '@/components/Chat.vue'

const props = defineProps<{
  courseId: number
  lessonId: number
}>()

const videoStore = useVideoStore()
const { currentVideo, loading, error } = storeToRefs(videoStore)

const videoPlayer = ref(null)
const player = ref(null)
const lesson = ref(null)
const chapters = ref([])
const videoUrl = ref('')
const showChat = ref(false)

// 响应式布局
const breakpoints = useBreakpoints({
  mobile: 768,
  tablet: 992,
  desktop: 1200,
})
const isMobile = computed(() => breakpoints.smaller('tablet'))

const defaultProps = {
  children: 'lessons',
  label: 'title'
}

const initializeVideo = async () => {
  try {
    await videoStore.fetchVideoData(props.lessonId)
    videoUrl.value = currentVideo.value.url
    
    player.value = videojs(videoPlayer.value, {
      controls: true,
      autoplay: false,
      preload: 'auto',
      fluid: true,
      responsive: true,
    })

    // 保存播放进度
    player.value.on('timeupdate', () => {
      const progress = Math.floor(player.value.currentTime())
      videoStore.saveProgress(props.lessonId, progress)
    })
  } catch (err) {
    console.error('Failed to initialize video:', err)
  }
}

const loadCourseStructure = async () => {
  const data = await getCourseStructure(props.courseId)
  chapters.value = data.chapters
  lesson.value = data.currentLesson
}

const handleNodeClick = (data) => {
  if (data.videoUrl) {
    videoUrl.value = data.videoUrl
    lesson.value = data
    player.value.src({ type: 'video/mp4', src: data.videoUrl })
  }
}

const formatDuration = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

const toggleChat = () => {
  showChat.value = !showChat.value
}

onMounted(async () => {
  await Promise.all([initializeVideo(), loadCourseStructure()])
})

onUnmounted(() => {
  if (player.value) {
    player.value.dispose()
  }
})
</script>

<style scoped>
.video-player-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  padding: 20px;
}

.video-player-container.mobile {
  grid-template-columns: 1fr;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  z-index: 1;
}

.error-message {
  margin: 10px 0;
}

@media (max-width: 768px) {
  .video-section {
    width: 100%;
  }

  .course-content {
    border-left: none;
    border-top: 1px solid #dcdfe6;
    padding-top: 20px;
  }
}
</style>
